<?php

namespace App\Http\Controllers\Plugin;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use OSS\OssClient;
use OSS\Core\OssException;
trait OssController
{
    public function commonUpload($image,$path='goods/images'){
        $domain = config('aliyun.oss.domain');
        Storage::makeDirectory('public/'.$path);
        $file_name = Str::random(6).'.'.$image->getClientOriginalExtension();
        $image->storeAs('public/'.$path,$file_name);
        $img =  'storage/'.$path.'/'.$file_name;
        self::ossUpload($path.'/'.$file_name,$img);
        Storage::delete('public/'.$path.'/'.$file_name);
        return $domain.$path.'/'.$file_name;
    }
    //生成二维码
    public function ercode($file){
        $domain = config('aliyun.oss.domain');
        //Storage::makeDirectory('public/'.$path);
        //$file_name = Str::random(6).'.'.$image->getClientOriginalExtension();
        //$image->storeAs('public/'.$path,$file_name);
        //$img =  'storage/'.$path.'/'.$file_name;
        $this->ossUpload($file,'qrcode');
        //Storage::delete('public/'.$path.'/'.$file_name);
        //return $domain.'qrcode/'.$file_name;
    }
    public static function ossUpload($object,$filePath)
    {
        $config = config('aliyun.defaults');
        $oss = config('aliyun.oss');
        try{
            $ossClient = new OssClient($config['accessKeyId'],$config['accessKeySecret'],$oss['endpoint']);
            $ossClient->uploadFile($oss['bucket'], $object, $filePath);
        }catch(OssException $e){
            info('阿里云上传失败'.$e->getMessage());
        }
        return $object;
    }
    /**
     * @param $object 为图片相对路径 前缀不加 ‘/’
     * @return mixed
     *
     */
    public function ossDelImg($object){
        $config = config('aliyun.defaults');
        $oss = config('aliyun.oss');
        try{
            $ossClient = new OssClient($config['accessKeyId'],$config['accessKeySecret'],$oss['endpoint']);
            $ossClient->deleteObject($oss['bucket'], $object);;
        }catch(OssException $e){
            info('阿里云删除失败'.$e->getMessage());
        }
        return $object;
    }
    //验证资源是否存在
    public  function doesObjectExist($bucket,$fileName)
    {
        $config = $this->config();
        $ossClient = $this->ossClient($config);
        return $ossClient->doesObjectExist($bucket,$fileName);
    }
    //oss签名 待操作
    public function ossSign(){

    }
}
